﻿using MultiDAQ_Analysis.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.Util
{
    public static class ChannelDataManager
    {
        private static string _dataDirectory;
        private static readonly object _lock = new object();

        private static string DataDirectory
        {
            get
            {
                if (_dataDirectory == null)
                {
                    lock (_lock)
                    {
                        if (_dataDirectory == null)
                        {
                            InitializeDataDirectory();
                        }
                    }
                }
                return _dataDirectory;
            }
        }

        private static void InitializeDataDirectory()
        {
            try
            {
                // 尝试使用应用程序启动路径
                string appPath = GetApplicationPath();
                _dataDirectory = Path.Combine(appPath, "ChannelData");

                // 确保数据目录存在
                if (!Directory.Exists(_dataDirectory))
                {
                    Directory.CreateDirectory(_dataDirectory);
                }
                else
                {
                    // 清理历史配置文件
                    CleanupOldConfigFiles();
                }
            }
            catch (Exception ex)
            {
                // 如果创建失败，使用临时目录
                System.Diagnostics.Debug.WriteLine($"无法创建数据目录，使用临时目录: {ex.Message}");
                _dataDirectory = Path.Combine(Path.GetTempPath(), "MultiDAQ_Analysis", "ChannelData");

                try
                {
                    if (!Directory.Exists(_dataDirectory))
                    {
                        Directory.CreateDirectory(_dataDirectory);
                    }
                    else
                    {
                        // 清理临时目录中的历史配置文件
                        CleanupOldConfigFiles();
                    }
                }
                catch (Exception tempEx)
                {
                    throw new InvalidOperationException($"无法创建数据存储目录: {tempEx.Message}", tempEx);
                }
            }
        }

        /// <summary>
        /// 清理重复的会话统计数据
        /// </summary>
        private static void CleanupDuplicateSessionStatistics(ChannelData channelData)
        {
            if (channelData.RealtimeStatistics?.SessionStatistics == null) return;

            // 使用 sessionId 和 startTime 作为唯一键去重，保留最新的记录
            var uniqueSessions = channelData.RealtimeStatistics.SessionStatistics
                .GroupBy(s => new { s.SessionId, s.StartTime })
                .Select(g => g.OrderByDescending(s => s.EndTime).First())
                .OrderBy(s => s.StartTime)
                .ToList();

            channelData.RealtimeStatistics.SessionStatistics = uniqueSessions;
        }

        /// <summary>
        /// 修改保存方法，增加去重
        /// </summary>
        public static bool SaveChannelData(int channelIndex, ChannelData data)
        {
            try
            {
                string dataDir = DataDirectory;
                string filePath = GetChannelFilePath(channelIndex);

                data.ChannelIndex = channelIndex;
                data.LastModified = DateTime.Now;

                if (data.RealtimeStatistics == null)
                {
                    data.RealtimeStatistics = new RealtimeStatisticsData();
                }

                // === 添加去重处理 ===
                CleanupDuplicateSessionStatistics(data);

                string jsonContent = JsonConvert.SerializeObject(data, Formatting.Indented);
                File.WriteAllText(filePath, jsonContent);
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存通道 {channelIndex + 1} 数据失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 清理所有通道的重复会话数据
        /// </summary>
        public static bool CleanupAllChannelDuplicates()
        {
            bool allSuccess = true;
           
            int channelCount = AppConfig.ChannelCount;

            for (int i = 0; i < channelCount; i++)
            {
                try
                {
                    var channelData = LoadChannelData(i);
                    CleanupDuplicateSessionStatistics(channelData);
                    if (!SaveChannelData(i, channelData))
                    {
                        allSuccess = false;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"清理通道 {i + 1} 重复数据失败: {ex.Message}");
                    allSuccess = false;
                }
            }

            return allSuccess;
        }

        /// <summary>
        /// 清理超出当前通道数量的历史配置文件
        /// </summary>
        private static void CleanupOldConfigFiles()
        {
            try
            {
                int currentChannelCount = AppConfig.ChannelCount;

                // 获取所有通道配置文件
                var allChannelFiles = Directory.GetFiles(DataDirectory, "channel_*.json");

                foreach (var filePath in allChannelFiles)
                {
                    // 从文件名中提取通道索引
                    string fileName = Path.GetFileNameWithoutExtension(filePath);
                    if (fileName.StartsWith("channel_") &&
                        int.TryParse(fileName.Substring(8), out int fileChannelIndex))
                    {
                        // 注意: 文件索引是从1开始的，而通道索引是从0开始的
                        int channelIndex = fileChannelIndex - 1;

                        // 如果通道索引超出当前配置的通道数量，删除该文件
                        if (channelIndex >= currentChannelCount)
                        {
                            File.Delete(filePath);
                            System.Diagnostics.Debug.WriteLine($"已删除历史配置文件: {fileName}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"清理历史配置文件时出错: {ex.Message}");
                // 不抛出异常，避免影响主要功能
            }
        }

        private static string GetApplicationPath()
        {
            try
            {
                if (Application.StartupPath != null)
                {
                    return Application.StartupPath;
                }
            }
            catch
            {
                // Application.StartupPath 可能不可用
            }

            try
            {
                return AppDomain.CurrentDomain.BaseDirectory;
            }
            catch
            {
                // 最后的备选方案
                return Environment.CurrentDirectory;
            }
        }

        private static string GetChannelFilePath(int channelIndex)
        {
            return Path.Combine(DataDirectory, $"channel_{channelIndex + 1}.json");
        }

        /// <summary>
        /// 加载指定通道的数据
        /// </summary>
        public static ChannelData LoadChannelData(int channelIndex)
        {
            try
            {
                string filePath = GetChannelFilePath(channelIndex);

                if (File.Exists(filePath))
                {
                    string jsonContent = File.ReadAllText(filePath);
                    if (!string.IsNullOrWhiteSpace(jsonContent))
                    {
                        var data = JsonConvert.DeserializeObject<ChannelData>(jsonContent);
                        if (data != null)
                        {
                            data.ChannelIndex = channelIndex; // 确保索引正确

                            // 确保统计数据对象存在
                            if (data.RealtimeStatistics == null)
                            {
                                data.RealtimeStatistics = new RealtimeStatisticsData();
                            }

                            return data;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载通道 {channelIndex + 1} 数据失败: {ex.Message}");
            }

            // 返回默认数据
            return CreateDefaultChannelData(channelIndex);
        }

        /// <summary>
        /// 创建默认通道数据
        /// </summary>
        private static ChannelData CreateDefaultChannelData(int channelIndex)
        {
            return new ChannelData
            {
                ChannelIndex = channelIndex,
                Thresholds = new ThresholdData(),
                WorkConditions = new WorkConditionData(),
                RealtimeStatistics = new RealtimeStatisticsData(),
                LastModified = DateTime.Now
            };
        }

        /// <summary>
        /// 保存指定通道的数据
        /// </summary>
        //public static bool SaveChannelData(int channelIndex, ChannelData data)
        //{
        //    try
        //    {
        //        // 确保数据目录存在
        //        string dataDir = DataDirectory; // 触发初始化

        //        string filePath = GetChannelFilePath(channelIndex);

        //        data.ChannelIndex = channelIndex;
        //        data.LastModified = DateTime.Now;

        //        // 确保统计数据对象存在
        //        if (data.RealtimeStatistics == null)
        //        {
        //            data.RealtimeStatistics = new RealtimeStatisticsData();
        //        }

        //        string jsonContent = JsonConvert.SerializeObject(data, Formatting.Indented);
        //        File.WriteAllText(filePath, jsonContent);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine($"保存通道 {channelIndex + 1} 数据失败: {ex.Message}");
        //        return false;
        //    }
        //}

        /// <summary>
        /// 加载所有通道的数据
        /// </summary>
        public static List<ChannelData> LoadAllChannelData()
        {
            int channelCount = AppConfig.ChannelCount;
            var allData = new List<ChannelData>();

            for (int i = 0; i < channelCount; i++)
            {
                allData.Add(LoadChannelData(i));
            }

            return allData;
        }

        /// <summary>
        /// 保存所有通道的数据
        /// </summary>
        public static bool SaveAllChannelData(List<ChannelData> allData)
        {
            bool allSuccess = true;

            for (int i = 0; i < allData.Count; i++)
            {
                if (!SaveChannelData(i, allData[i]))
                {
                    allSuccess = false;
                }
            }

            return allSuccess;
        }

        /// <summary>
        /// 删除指定通道的数据文件
        /// </summary>
        public static bool DeleteChannelData(int channelIndex)
        {
            try
            {
                string filePath = GetChannelFilePath(channelIndex);

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"删除通道 {channelIndex + 1} 数据失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 检查数据目录是否可用
        /// </summary>
        public static bool IsDataDirectoryAvailable()
        {
            try
            {
                string dataDir = DataDirectory;
                return Directory.Exists(dataDir);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取数据目录路径（用于调试）
        /// </summary>
        public static string GetDataDirectoryPath()
        {
            try
            {
                return DataDirectory;
            }
            catch (Exception ex)
            {
                return $"获取路径失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 备份所有通道数据
        /// </summary>
        public static bool BackupAllData(string backupFilePath)
        {
            try
            {
                var allData = LoadAllChannelData();
                string jsonContent = JsonConvert.SerializeObject(allData, Formatting.Indented);
                File.WriteAllText(backupFilePath, jsonContent);
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"备份数据失败: {ex.Message}");
                return false;
            }
        }

        // 获取所有选中通道的方法
        public static List<ChannelData> GetSelectedChannels()
        {
            // 加载所有通道数据
            List<ChannelData> allChannels = ChannelDataManager.LoadAllChannelData();

            // 筛选出 IsSelected 为 true 的通道
            List<ChannelData> selectedChannels = allChannels
                .Where(channel => channel.Thresholds?.IsSelected ?? true) // 使用 null 条件运算符和安全访问
                .ToList();

            return selectedChannels;
        }

        /// <summary>
        /// 从备份文件恢复数据
        /// </summary>
        public static bool RestoreFromBackup(string backupFilePath)
        {
            try
            {
                if (!File.Exists(backupFilePath))
                {
                    return false;
                }

                string jsonContent = File.ReadAllText(backupFilePath);
                var allData = JsonConvert.DeserializeObject<List<ChannelData>>(jsonContent);

                if (allData != null)
                {
                    return SaveAllChannelData(allData);
                }
                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"恢复数据失败: {ex.Message}");
                return false;
            }
        }

        // ===============================
        // 新增：统计数据相关方法
        // ===============================

        /// <summary>
        /// 更新指定通道的统计数据
        /// </summary>
        public static bool UpdateChannelStatistics(int channelIndex, long alphaCount, long betaCount, long deductedCount, long sampleCount)
        {
            try
            {
                var channelData = LoadChannelData(channelIndex);
                channelData.RealtimeStatistics.UpdateStatistics(alphaCount, betaCount, deductedCount, sampleCount);
                return SaveChannelData(channelIndex, channelData);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新通道 {channelIndex + 1} 统计数据失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 重置指定通道的统计数据
        /// </summary>
        public static bool ResetChannelStatistics(int channelIndex)
        {
            try
            {
                var channelData = LoadChannelData(channelIndex);
                channelData.RealtimeStatistics.ResetStatistics();
                return SaveChannelData(channelIndex, channelData);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"重置通道 {channelIndex + 1} 统计数据失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 重置所有通道的统计数据
        /// </summary>
        public static bool ResetAllChannelStatistics()
        {
            bool allSuccess = true;
            int channelCount = AppConfig.ChannelCount;

            for (int i = 0; i < channelCount; i++)
            {
                if (!ResetChannelStatistics(i))
                {
                    allSuccess = false;
                }
            }

            return allSuccess;
        }

        /// <summary>
        /// 获取指定通道的统计数据
        /// </summary>
        public static RealtimeStatisticsData GetChannelStatistics(int channelIndex)
        {
            try
            {
                var channelData = LoadChannelData(channelIndex);
                return channelData.RealtimeStatistics ?? new RealtimeStatisticsData();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道 {channelIndex + 1} 统计数据失败: {ex.Message}");
                return new RealtimeStatisticsData();
            }
        }

        /// <summary>
        /// 获取所有通道的统计数据
        /// </summary>
        public static Dictionary<int, RealtimeStatisticsData> GetAllChannelStatistics()
        {
            var statistics = new Dictionary<int, RealtimeStatisticsData>();
            int channelCount = AppConfig.ChannelCount;

            for (int i = 0; i < channelCount; i++)
            {
                statistics[i] = GetChannelStatistics(i);
            }

            return statistics;
        }



        /// <summary>
        /// 结束当前统计会话 - 不保存历史会话
        /// </summary>
        public static bool EndStatisticsSession(string sessionName = null)
        {
            try
            {
                var allData = LoadAllChannelData();

                foreach (var channelData in allData)
                {
                    // 只更新最后修改时间，不保存到历史会话
                    channelData.RealtimeStatistics.LastUpdateTime = DateTime.Now;
                }

                return SaveAllChannelData(allData);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"结束统计会话失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 开始新的统计会话 - 不保存历史会话
        /// </summary>
        public static bool StartStatisticsSession(string sessionName = null)
        {
            try
            {
                var allData = LoadAllChannelData();

                foreach (var channelData in allData)
                {
                    // 直接重置统计，不保存历史
                    channelData.RealtimeStatistics.ResetStatistics();
                    // 清空历史会话数据
                    channelData.RealtimeStatistics.SessionStatistics.Clear();
                }

                return SaveAllChannelData(allData);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"开始统计会话失败: {ex.Message}");
                return false;
            }
        }



    }
}